<?php
namespace app\lawcase\controller;

use app\base\BaseController;
use app\lawcase\model\CaseCause as CaseCauseModel;
use app\lawcase\validate\CaseCauseCheck;
use think\facade\Db;
use think\facade\View;

/**
 * 案由管理控制器
 */
class CaseCause extends BaseController
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new CaseCauseModel();
    }

    // 案由列表
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = [];
            if (!empty($param['keywords'])) {
                $where[] = ['name', 'like', '%' . $param['keywords'] . '%'];
            }

            try {
                $rows = 10000; // 设置一个较大的数值，实际上不会用到分页
                $content = $this->model->getList($where, $rows, $param) ?: [];

                $list = $this->model->buildTreeFromList($content);
            } catch (\Exception $e) {
                $list = [];  // 处理异常，确保返回空数组
                $content = [];
            }
            // 确保 list 是数组
            $count = count($content);
            $list = is_array($list) ? $list : [];

            return table_assign(0, '', ['data' => $list, 'count' => $count]);
        } else {
            return view();
        }
    }

    // 添加案由
    public function add()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $param['parent_id'] = $param['parent_id'] ?? 0;
            $param['sort'] = $param['sort'] ?? 100;

            // 使用验证器进行数据验证
            try {
                $validate = validate(CaseCauseCheck::class);
                if (!$validate->scene('add')->check($param)) {
                    return to_assign(1, $validate->getError());
                }
            } catch (\Exception $e) {
                return to_assign(1, $e->getMessage());
            }
            // 添加案由，框架会自动处理返回值
            return $this->model->add($param);
        } else {
            $pid = input('pid', 0);
            $detail = [
                'id' => 0,
                'parent_id' => $pid,
                'name' => '',
                'sort' => 100
            ];
            $parentOptions = $this->model->getSelectData();
            View::assign([
                'detail' => $detail,
                'parentOptions' => $parentOptions
            ]);
            return view();
        }
    }

    // 修改案由
    public function edit()
    {
        if (request()->isAjax()) {
            $param = get_params();
          
            // 使用验证器进行数据验证
            try {
                $validate = validate(CaseCauseCheck::class);
                if (!$validate->scene('edit')->check($param)) {
                    return to_assign(1, $validate->getError());
                }
            } catch (\Exception $e) {
                return to_assign(1, $e->getMessage());
            }

            // 编辑案由，框架会自动处理返回值
            return $this->model->edit($param);

        } else {
            $id = input('id', 0);
            $detail = $this->model->getDetail($id);
            if (!empty($detail)) {
                $parentOptions = $this->model->getSelectData();
                View::assign([
                    'detail' => $detail,
                    'parentOptions' => $parentOptions
                ]);
                return view('add');
            } else {
                return to_assign(1, '案由不存在');
            }
        }
    }

    // 删除案由
    public function delete()
    {
        $id = get_params("id");
        return $this->model->remove($id);
    }

    // 案由排序
    public function sort()
    {
        $data = get_params();
        $result = $this->model->updateSort($data);
        $id = $data['id'] ?? 0;
        $sort = isset($data['sort']) ? $data['sort'] : 0;
        return to_assign($result ?0 : 1, $result ? '排序更新成功' : '排序更新失败');
    }

    // 获取案由选择列表
    public function getSelectList()
    {
        $data = $this->model->getSelectData()?: [];
        return to_assign(0, '', $data);
    }
}